/**
 * 文件上传下载管理业务逻辑类
 */
package net.ssta.util.fileUpload;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import net.ssta.common.Constants;
import net.ssta.core.util.UUIDGenerator;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.log4j.Logger;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * @author Administrator
 * 
 */
public class FileUploadManagerHandler
{
    /**
     * 日志记录
     */
    private static Logger log =
        Logger.getLogger(FileUploadManagerServlet.class);
    
    
    
    /**
     * 保存客户端上传过来的文件到本地目录,返回文件名和相对路径
     * 
     * @throws IOException
     * @throws FileUploadException
     */
    public String[] savePhoto(HttpServletRequest request)
    {
        return savePhoto(request, "");
    }
    
    /**
     * 保存客户端上传过来的照片到本地目录,返回原文件名和相对路径
     * 
     * @param strUUID 文档上传的默认文件名 UUID
     * @throws IOException
     * @throws FileUploadException
     */
    public String[] savePhoto(HttpServletRequest request, String imageUuid)
    {
        String[] strArr = new String[3];
        Map<String, String> kv = new HashMap<String, String>();
        String realpath = request.getRealPath("/")+Constants.PIC_UPLOAD_PATH;
        
        
        //判断upload目录是否存在
        File filepath = new File(realpath);
        
        
        if (!filepath.exists() || !filepath.isDirectory())
        {
            if (!filepath.mkdirs())
            {
                log.debug("创建不存在的文件夹：" + realpath);
                return null;
            }
            
        }
        
        if (ServletFileUpload.isMultipartContent(request))
        {
            // 创建该对象
            DiskFileItemFactory dff = new DiskFileItemFactory();
            // 指定上传文件的临时目录
            dff.setRepository(filepath);
            
            // 指定在内存中缓存数据大小,单位为byte
            dff.setSizeThreshold(Constants.TMP_FILE_SIZE);
            // 创建该对象
            ServletFileUpload sfu = new ServletFileUpload(dff);
            // 指定单个上传文件的最大值
            sfu.setSizeMax(Constants.FILE_MAX_SIZE);
            
            FileItemIterator fii;
            BufferedInputStream in = null;
            BufferedOutputStream out = null;
            try
            {
                fii = sfu.getItemIterator(request);
                // 解析request
                // 请求,并返回FileItemIterator集合
                while (fii.hasNext())
                {
                    // 从集合中获得一个文件流
                    FileItemStream fis = fii.next();
                    // 过滤掉表单中非文件域
                    if (!fis.isFormField() && fis.getName().length() > 0)
                    {
                    	
                        // 保存的文件名为UUID
                    	String expid = request.getParameter("expid");
                    	if(expid==null||expid.equals("")){
                    		expid="none";
                    	}
                    	
                    	
                        String strFileName = fis.getName();
                        String strExt = strFileName.substring(strFileName.lastIndexOf("."));
                        String fileName = expid + strExt.toLowerCase();
                        
                        
                        
                        // 获得文件输入流
                        in = new BufferedInputStream(fis.openStream());
                        
                        // 获得文件输出流
                        out = new BufferedOutputStream(new FileOutputStream(new File(filepath + File.separator + fileName)));
                        
                        // 开始把文件写到你指定的上传文件夹
                        Streams.copy(in, out, true);
                        
                        
                        
                        // 文件的相对路径
                        strArr[0] = Constants.PIC_UPLOAD_PATH + "/" + fileName;
                        
                        //上传前文件的名称
                        strArr[1] = strFileName;
                        
                        strArr[2] = expid;
                        
                        in.close();
                        out.close();
                    }
                }
            }
            catch (FileUploadException e)
            {
                log.error("文件上传失败 FileUploadException:", e);
            }
            catch (IOException e)
            {
                log.error("文件上传IOException:", e);
            }
            finally
            {
                if (null != in)
                {
                    try
                    {
                        in.close();
                    }
                    catch (IOException e)
                    {
                        log.error("文件上传IOException:", e);
                    }
                }
                if (null != out)
                {
                    try
                    {
                        out.close();
                    }
                    catch (IOException e)
                    {
                        log.error("文件上传IOException:", e);
                    }
                }
            }
        }
        return strArr;
    }
    
    
}
